#ifndef DATABASEHANDLER_H
#define DATABASEHANDLER_H

#include <QObject>
#include <QString>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QVariantMap>
#include <QVariantList>
#include "devicecontroller.h"
#include "samplingmanager.h"
#include "auditlogger.h"

class DatabaseHandler : public QObject
{
    Q_OBJECT

public:
    explicit DatabaseHandler(QObject *parent = nullptr);
    ~DatabaseHandler();

    // Database initialization
    bool initialize(const QString& databasePath = "", const QString& encryptionKey = "");
    bool createTables();
    bool isConnected() const;
    void closeDatabase();

    // User management database operations
    bool insertUser(const QString& username, const QString& passwordHash, 
                   const QString& salt, const QString& fullName, 
                   const QString& role, const QString& email = "");
    bool updateUser(const QString& username, const QVariantMap& userData);
    bool deleteUser(const QString& username);
    QVariantMap getUser(const QString& username) const;
    QVariantList getAllUsers() const;
    bool updateUserLastLogin(const QString& username);

    // Sampling data operations
    bool insertSamplingRecord(const SamplingRecord& record);
    bool updateSamplingRecord(int recordId, const SamplingRecord& record);
    bool deleteSamplingRecord(int recordId);
    QVariantList getSamplingRecords(const QDateTime& fromDate = QDateTime(), 
                                   const QDateTime& toDate = QDateTime(),
                                   const QString& operatorId = "") const;
    QVariantMap getSamplingStatistics(int days = 30) const;

    // Sampling task operations
    bool insertSamplingTask(const SamplingTask& task);
    bool updateSamplingTask(int taskId, const SamplingTask& task);
    bool deleteSamplingTask(int taskId);
    QVariantList getSamplingTasks(bool activeOnly = false) const;
    QVariantMap getSamplingTask(int taskId) const;

    // Device parameter logging
    bool insertDeviceParameters(const DeviceParameters& params, const QString& operatorId);
    QVariantList getDeviceParameterHistory(const QDateTime& fromDate = QDateTime(),
                                          const QDateTime& toDate = QDateTime()) const;

    // Audit log operations
    bool insertAuditLog(const AuditLogger::AuditRecord& record);
    QVariantList getAuditLogs(const QDateTime& fromDate = QDateTime(),
                             const QDateTime& toDate = QDateTime(),
                             const QString& userId = "",
                             const QString& action = "") const;
    bool cleanupOldAuditLogs(int retentionDays = 90);

    // System configuration
    bool setSetting(const QString& key, const QVariant& value);
    QVariant getSetting(const QString& key, const QVariant& defaultValue = QVariant()) const;
    QVariantMap getAllSettings() const;
    bool deleteSetting(const QString& key);

    // Data maintenance
    bool vacuum();
    bool backup(const QString& backupPath);
    bool restore(const QString& backupPath);
    qint64 getDatabaseSize() const;
    bool cleanupOldRecords(int retentionDays = 365);

    // Transaction support
    bool beginTransaction();
    bool commitTransaction();
    bool rollbackTransaction();

    // Error handling
    QString getLastError() const;
    QString lastError() const;  // 添加 lastError 方法
    bool hasError() const;
    
    // 添加缺失的方法声明
    bool connect();
    QSqlDatabase& database();
    bool userExists(const QString& username) const;
    bool addUser(const QString& username, const QString& password, const QString& role);
    QString databasePath() const;
    QString getEncryptionPassword() const;
    bool isEncrypted() const;
    QString hashPassword(const QString& password) const;
    bool executeScript(const QString& scriptPath);
    bool applyEncryption(const QString& password);
    bool verifyEncryption() const;

signals:
    void databaseError(const QString& error);
    void errorOccurred(const QString& error);  // 添加 errorOccurred 信号
    void recordInserted(const QString& tableName, int recordId);
    void recordUpdated(const QString& tableName, int recordId);
    void recordDeleted(const QString& tableName, int recordId);

private:
    // Private methods
    bool executeQuery(const QString& queryStr, const QVariantList& bindValues = QVariantList());
    QSqlQuery prepareQuery(const QString& queryStr) const;
    bool createUsersTable();
    bool createSamplingRecordsTable();
    bool createSamplingTasksTable();
    bool createDeviceParametersTable();
    bool createAuditLogsTable();
    bool createSettingsTable();
    bool checkTableExists(const QString& tableName) const;
    QString samplingModeToString(SamplingMode mode) const;
    SamplingMode stringToSamplingMode(const QString& modeStr) const;
    QString samplingStatusToString(ScheduleStatus status) const;
    ScheduleStatus stringToSamplingStatus(const QString& statusStr) const;
    QString deviceStatusToString(DeviceStatus status) const;
    DeviceStatus stringToDeviceStatus(const QString& statusStr) const;

    // Member variables
    QSqlDatabase m_database;
    QSqlDatabase m_db;  // 添加 m_db 成员变量
    QString m_databasePath;
    QString m_dbPath;   // 添加 m_dbPath 成员变量
    QString m_lastError;
    QString m_encryptionPassword;  // 添加加密密码成员变量
    bool m_isConnected;
    bool m_encrypted;   // 添加加密状态成员变量
    static int s_connectionCounter;
};

#endif // DATABASEHANDLER_H